HarmonyOS-鸿蒙app开发 —基于java控制类小器件_Vibrator开发指导

HarmonyOS-鸿蒙app开发 —基于java控制类小器件_Vibrator开发指导

场景介绍

当设备需要设置不同的振动效果时,可以调用Vibrator模块,例如,设备的按键可以设置不同强度和时长的振动,闹钟和来电可以设置不同强度和时长的单次或周期性振动。

接口说明

振动器模块主要提供的功能有:查询设备上振动器的列表,查询某个振动器是否支持某种振动效果,触发和关闭振动器。VibratorAgent类开放能力如下,具体请查阅API参考文档。

表1 VibratorAgent的主要接口

接口名

描述

getVibratorIdList()

获取硬件设备上的振动器列表。

isSupport(int)

根据指定的振动器Id查询硬件设备是否存在该振动器。

isEffectSupport(int, String)

查询指定的振动器是否支持指定的震动效果。

startOnce(int, String)

对指定的振动器创建指定效果的一次性振动。

startOnce​(String)

对指定的振动器创建指定效果的一次性振动。

startOnce(int, int)

对指定的振动器创建指定振动时长的一次性振动。

startOnce​(int)

对指定的振动器创建指定振动时长的一次性振动。

start(String, boolean)

对指定的振动器以预设的某种振动效果进行循环振动。

start(int, VibrationPattern)

对指定的振动器创建自定义效果的波形或一次性振动。

start​(VibrationPattern)

对指定的振动器创建自定义效果的波形或一次性振动。

stop(int, String)

关闭指定的振动器指定模式的振动。

stop(String)

关闭指定的振动器指定模式的振动。

开发步骤

控制设备上的振动器,需要在“config.json”里面进行配置请求权限。具体如下:

“reqPermissions”: [

{

“name”: “ohos.permission.VIBRATE”,

“reason”: “”,

“usedScene”: {

“ability”: [

“.MainAbility”

],

“when”: “inuse”

}

}

]

  1. 查询硬件设备上的振动器列表。
  2. 查询指定的振动器是否支持指定的震动效果。
  3. 创建不同效果的振动。

关闭指定的振动器指定模式的振动。

private VibratorAgent vibratorAgent = new VibratorAgent();

 

private int[] timing = {1000, 1000, 2000, 5000};

 

private int[] intensity = {50, 100, 200, 255};

 

@Override

public void onStart(Intent intent) {

super.onStart(intent);

super.setUIContent(ResourceTable.Layout_vibrator_layout);

 

// …

 

// 查询硬件设备上的振动器列表

List<Integer> vibratorList = vibratorAgent.getVibratorIdList();

if (vibratorList.isEmpty()) {

return;

}

int vibratorId = vibratorList.get(0);

 

// 查询指定的振动器是否支持指定的振动效果

boolean isSupport = vibratorAgent.isEffectSupport(vibratorId,

VibrationPattern.VIBRATOR_TYPE_CAMERA_CLICK);

 

// 创建指定效果的一次性振动

boolean vibrateEffectResult = vibratorAgent.startOnce(vibratorId,

VibrationPattern.VIBRATOR_TYPE_CAMERA_CLICK);

 

// 创建指定振动时长的一次性振动

int vibratorTiming = 1000;

boolean vibrateResult = vibratorAgent.startOnce(vibratorId, vibratorTiming);

 

// 以预设的某种振动效果进行循环振动

boolean vibratorRepeatEffect = vibratorAgent.start(VibrationPattern.VIBRATOR_TYPE_RINGTONE_BOUNCE, true);

// 控制振动器停止循环振动

vibratorAgent.stop();

 

// 创建自定义效果的周期性波形振动

int count = 5;

VibrationPattern vibrationPeriodEffect = VibrationPattern.createPeriod(timing, intensity, count);

boolean vibratePeriodResult = vibratorAgent.start(vibratorId, vibrationPeriodEffect);

 

// 创建自定义效果的一次性振动

VibrationPattern vibrationOnceEffect = VibrationPattern.createSingle(3000, 50);

boolean vibrateSingleResult = vibratorAgent.start(vibratorId, vibrationOnceEffect);

 

// 关闭指定的振动器自定义模式的振动

boolean stopResult = vibratorAgent.stop(vibratorId,

VibratorAgent.VIBRATOR_STOP_MODE_CUSTOMIZED);

}

0 0 投票数
文章评分
订阅评论
提醒
0 评论
最旧
最新 最多投票
内联反馈
查看所有评论
0
希望看到您的想法,请您发表评论x